package com.sunchen.asc.service.user.server;

import cn.hutool.core.collection.CollUtil;
import com.sunchen.asc.service.constant.RedisConstant;
import com.sunchen.asc.service.user.domain.Resource;
import com.sunchen.asc.service.user.domain.Role;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 资源与角色配置管理
 */
@Service
@Slf4j
public class ResourceServiceImpl {
    private Map<String, List<String>> resourceRolesMap;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    public void resourceRoleSync(List<Role> roles){
        resourceRolesMap = new TreeMap<>();
        for (Role role:roles){
            List<Resource> resources= role.getResources();
            for (Resource resource:resources){
                //该资源已存在
                if (resourceRolesMap.get(resource.getUrl())!=null){
                    List<String> roleList = resourceRolesMap.get(resource.getUrl());
                    //若包含当前角色
                    if (roleList.contains(role.getName())){

                    }else{
                        roleList.add(role.getName());
                        resourceRolesMap.put(resource.getUrl(),roleList);
                    }
                }else {
                    resourceRolesMap.put(resource.getUrl(), CollUtil.toList(role.getName()));
                }
            }
        }
        log.debug("更新资源与角色配置缓存，更新值为{}",resourceRolesMap);
        redisTemplate.opsForHash().putAll(RedisConstant.RESOURCE_ROLES_MAP,resourceRolesMap);

    }
}
